<?php
namespace app\index\controller;

use think\Controller;
use app\index\model\Product;

class Index extends Controller
{
    public function __construct(){

    }
    public function index()
    {
        $this->redirect('products/index');
    }

    public function table(){
        $thisWeek = week_day(time());
        $lastWeek = week_day(strtotime('-7 days'));

        $prod = new Product();
        $thisData = $prod->getProductStatic($thisWeek[0],$thisWeek[1]);
        $lastData = $prod->getProductStatic($lastWeek[0],$lastWeek[1]);

        $res = $this->_handle_data($thisData,$lastData);

        //echo "<pre>";
        //var_dump($res);
        //echo "</pre>";

        return view('table',['data'=>$res]);
    }

    public function _handle_data(array $th,array $la){
        // 索引上周的产品
        $last = [];
        foreach ($la as $val){
            $last[$val['prod_id']] = $val;
        }

        $result = [];
        foreach($th as $val){
            $result[$val['product']]['本周'] = $val;

            if(!isset($last[$val['prod_id']])){
                $tmp = [];
                $tmp1 = [];
                foreach ($val as $k => $v){
                    $tmp[$k] = 0;
                    $tmp1[$k] = 1;

                    if(0 == $v){
                        $tmp1[$k] = 0;
                    }
                    $tmp1[$k] *= 100;
                    $tmp1[$k] .= '%';
                }
                $result[$val['product']]['上周'] = $tmp;
                $result[$val['product']]['环比'] = $tmp1;
                continue;
            }
            $result[$val['product']]['上周'] = $last[$val['prod_id']];

            // 计算环比
            $tmp = [];
            foreach ($val as $k => $v){
                if(0 == $last[$val['prod_id']][$k]){
                    $tmp[$k] = 1;
                    if(0 == $v){
                        $tmp[$k] = 0;
                    }
                    $tmp[$k] *= 100;
                    $tmp[$k] .= '%';
                    continue;
                }

                $tmp[$k] = round((($v - $last[$val['prod_id']][$k]) / $last[$val['prod_id']][$k]),2);
                $tmp[$k] *= 100;
                $tmp[$k] .= '%';
            }
            $result[$val['product']]['环比'] = $tmp;

        }

        return $result;
    }
}
